package source.xml
{
	import flash.events.*;
	import flash.net.*;

	public class XMLManager extends EventDispatcher implements IXMLManager
	{
		
		public static const UNAVAILABLE:Number = 0;
		public static const LOADING:Number = 1;
		public static const AVAILABLE:Number = 2;
		
		public static const STATE_CHANGE:String = 'STATE_CHANGE';
		
		protected var state:Number;
		
		protected var url:String;
		protected var loader:URLLoader;
		protected var service:XML;
		
	
		/**
		 * 
		 */	
		public function XMLManager( url:String ) 
		{
			
			setState( XMLManager.UNAVAILABLE );
			this.url = url;
			load();
			
		}
		
		public function load():void
		{
			
			loader = new URLLoader();
			loader.dataFormat = URLLoaderDataFormat.TEXT;
			loader.addEventListener( Event.COMPLETE, setService );
			loader.load( new URLRequest( url ) );
			
		}
		
		public function unload():void
		{
			
			loader.removeEventListener( Event.COMPLETE, setService );
			loader = null;
			
		}
		
		public function refresh():void
		{
		
			setState( XMLManager.LOADING );	
			load();
			
		}
		
		public function getState():Number
		{
			
			return state;
			
		}
		
		public function getService():XML
		{
			
			return service;
			
		}
				
		protected function setService( event:Event ):void 
		{
						
			try
			{
				
				if( service )
				{
					
					service = null;
					
				}
				
				service = new XML( event.target.data );
				setState( XMLManager.AVAILABLE );
				unload();
			
			} catch( error:Error ) {
				
				trace( 'Could not parse text into XML' );
				setState( XMLManager.UNAVAILABLE );
				
			}
			
		}
		
		protected function setState( state:Number ):void
		{
			
			if( this.state == state )
			{
				
				return;
				
			} else {
				
				this.state = state;
				dispatchEvent( new Event( XMLManager.STATE_CHANGE ) );
				
			}
			
		}
		
	}
	
}